package com.corpgovernment.organization.factory;

import com.corpgovernment.api.basic.enums.SourceEnum;
import com.corpgovernment.common.base.CommonException;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.service.impl.AbstractLoginSourceService;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author jhxue
 * @create 2022-02-18-14:25
 */
@Component
public class LoginSourceServiceFactory {


	@Autowired
	private List<AbstractLoginSourceService> loginSourceServiceList;

	private volatile Map<String, AbstractLoginSourceService> loginSourceServiceMap;

	@PostConstruct
	private void init() {
		Map<String, AbstractLoginSourceService> loginServiceHashMap = Maps.newHashMapWithExpectedSize(loginSourceServiceList.size());
		for (AbstractLoginSourceService loginSourceService : loginSourceServiceList) {
			for (SourceEnum sourceEnum : loginSourceService.getLoginSource()) {
				loginServiceHashMap.put(sourceEnum.toString(), loginSourceService);
			}
		}
		loginSourceServiceMap = loginServiceHashMap;
	}

	public AbstractLoginSourceService getLoginSourceService(String source) {
		return Optional.ofNullable(loginSourceServiceMap.get(source)).orElseThrow(() -> new CorpBusinessException(OrganizationResponseCodeEnum.NO_SUCH_LOGIN_SOURCE_SERVICE));
	}

}
